package com.renli.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCUtils {

    private static DruidDataSource dataSource = null; // 使用Druid数据源
    private static ThreadLocal<Connection> connectionThreadLocal = ThreadLocal.withInitial(() -> {
        try {
            if (dataSource == null) {
                initializeDataSource(); // 初始化数据源
            }
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("Failed to get a database connection.", e);
        }
    });

    // 获取日志记录器
    private static final Logger logger = LogManager.getLogger(JDBCUtils.class);

    // 初始化数据源
    private static void initializeDataSource() {
        dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test-layui");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        // 配置其他数据源属性
        dataSource.setInitialSize(5); // 初始化连接数
        dataSource.setMaxActive(20); // 最大活动连接数
        // 其他配置...

        // 可以添加其他数据源配置
    }

    // 获取数据库连接
    public static Connection getConnection() {
        return connectionThreadLocal.get();
    }

    // 开启事务
    public static void beginTransaction() {
        Connection connection = getConnection();
        try {
            connection.setAutoCommit(false); // 设置手动提交
        } catch (SQLException e) {
            throw new RuntimeException("Failed to begin transaction.", e);
        }
    }

    // 提交事务
    public static void commitTransaction() {
        Connection connection = getConnection();
        try {
            connection.commit();
        } catch (SQLException e) {
            throw new RuntimeException("Failed to commit transaction.", e);
        }
    }

    // 回滚事务
    public static void rollbackTransaction() {
        Connection connection = getConnection();
        try {
            connection.rollback();
        } catch (SQLException e) {
            throw new RuntimeException("Failed to rollback transaction.", e);
        }
    }

    // 关闭连接
    public static void closeConnection() {
        Connection connection = connectionThreadLocal.get();
        if (connection != null) {
            try {
                connection.close();
                connectionThreadLocal.remove();
            } catch (SQLException e) {
                throw new RuntimeException("Failed to close connection.", e);
            }
        }
    }

    // 执行查询操作
    public static ResultSet executeQuery(String sql, Object... params) throws SQLException {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }

        // 记录日志
        logger.info("Executing SQL query: {}", sql);

        return preparedStatement.executeQuery();
    }

    // 执行更新操作
    public static int executeUpdate(String sql, Object... params) throws SQLException {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }

        // 记录日志
        logger.info("Executing SQL update: {}", sql);

        return preparedStatement.executeUpdate();
    }


    private static Object execute(String sql, Object... params) throws SQLException {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }

        // 根据SQL语句中的关键字来确定操作类型
        boolean isSelectQuery = sql.trim().toLowerCase().startsWith("select");

        // 记录日志
        if (isSelectQuery) {
            logger.info("Executing SQL query: {}", sql);
            return preparedStatement.executeQuery();
        } else {
            logger.info("Executing SQL update: {}", sql);
            int rowsAffected = preparedStatement.executeUpdate();
            // 如果需要获取生成的主键等信息，可以在这里添加代码
            return rowsAffected;
        }
    }

    public static void main(String[] args) {
        Connection connection = getConnection();
        System.out.println(connection);
        System.out.println(connection == getConnection());
    }
}


